<template>
<div class="adoptedList">
  <search-block type="wrap-block">
    <el-form inline :model="search" label-width="100px">
      <el-form-item label="编号:">
        <el-input v-model="search.adoptedSn" clearable></el-input>
      </el-form-item>
      <el-form-item label="名称:">
        <el-input v-model="search.adoptedName" clearable></el-input>
      </el-form-item>
      <el-form-item label="品种:">
        <el-cascader
          v-model="varietyVal"
          clearable
          :options="cateData"
          :props="{
          label: 'cateName',
          value: 'cateCode'
          }"></el-cascader>
      </el-form-item>
      <el-form-item label="主人:">
        <el-input v-model="search.adoptedUserName" clearable></el-input>
      </el-form-item>
      <el-form-item label="是否建档:">
        <el-select v-model="search.status" clearable>
          <el-option label="未建档" value="0"></el-option>
          <el-option label="已建档" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="当前阶段:">
        <el-select v-model="search.adoptedStatus" clearable>
          <el-option
            v-for="item in adoptedStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template slot="button">
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="searchTable(true)">查询</el-button>
<!--      <el-button type="primary" @click="importVisible = true">批量导入</el-button>-->
    </template>
  </search-block>
  <y-table
    ref="table"
    border
    pagination
    :getDataWay="getDataWay"
    :columns="columns">
    <el-table-column slot="avatarUrl" label="头像" align="center" header-align="center" width="125">
      <template v-slot="{row}">
        <img v-if="row.avatarUrl" style="height: 100px" :src="generateMediaUrl({fileOpenUrl: row.avatarUrl})"/>
      </template>
    </el-table-column>
    <el-table-column slot="variety" label="物种|品种" align="center" header-align="center" min-width="120">
      <template v-slot="{row}">
        <span style="display: block">[{{row.adoptName || row.adoptedName}}]</span>
        <span style="display: block">{{getVarietyName(row.kind, row.variety)}}</span>
      </template>
    </el-table-column>
    <el-table-column slot="status" label="建档操作" align="center" header-align="center" width="80">
      <template v-slot="{row}">
        <span class="y-success" v-if="row.status === '1' || row.status === '2'">已建档</span>
        <span class="y-danger" v-else>未建档</span>
      </template>
    </el-table-column>
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="190" fixed="right">
      <template v-slot="{row}">
        <div class="wrap-table-buttons">
          <el-button size="mini" @click="showGuardian(row)" style="width: 80px">主人</el-button>
          <el-button :type="!row.adoptedStatus || ['0','1','3'].includes(row.adoptedStatus) ? 'primary' : undefined" size="mini" @click="editStatus(row)">成长档案</el-button>
          <el-popconfirm
            title="该物品确认可收获？"
            v-if="(row.status === '1' || row.status === '2') && row.adoptedStatus === '0'"
            @confirm="toHarvest(row)">
            <el-button slot="reference" type="primary" size="mini" style="width: 80px">可收获</el-button>
          </el-popconfirm>
          <el-popconfirm
            title="建档一旦完成不可取消，请确定是否建档？"
            v-if="row.status !== '1' && row.status !== '2' && !!row.adoptedSn"
            @confirm="confirmStatus(row)">
            <el-button slot="reference" type="primary" size="mini">完成建档</el-button>
          </el-popconfirm>
          <el-button size="mini" @click="viewOrder(row)">订单</el-button>
          <el-popconfirm
            title="该物品确认可退款？"
            v-if="row.status === '1' && row.adoptedStatus === '0'"
            @confirm="openRefund(row)">
            <el-button slot="reference" type="danger" size="mini">可以退货</el-button>
          </el-popconfirm>
          <div class="y-danger" style="width: 80px" v-else-if="row.status === '2'">可以退货</div>
        </div>
      </template>
    </el-table-column>
  </y-table>
  <el-drawer
    :visible.sync="orderForms.showForm"
    title="订单详情"
    :size="800"
    destroy-on-close>
    <adopt-order-info
      v-if="orderForms.currentForm"
      :order-id="orderForms.currentForm.orderId"></adopt-order-info>
  </el-drawer>
  <el-drawer
    :visible.sync="importVisible"
    title="成长档案批量导入"
    :size="800"
    destroy-on-close>
    <adopted-details-batch></adopted-details-batch>
  </el-drawer>
  <el-drawer
    :key="refreshKey"
    :visible.sync="forms.showForm"
    :title="'成长档案【' + forms.adoptedName + '】'"
    :size="1000"
    destroy-on-close>
    <adopted-details
      :adopted-id="forms.adoptedId"
      :is-edit="forms.isEdit"
      @close="closeDrawer">
    </adopted-details>
  </el-drawer>
  <el-dialog
    v-if="guardianForms.row.id && guardianForms.row.id"
    :visible.sync="guardianForms.showForm"
    :title="`【${guardianForms.row.adoptedName}】买方信息`"
    width="50%"
    @opened="onOpenGuardianPerson"
    @closed="hideGuardianPerson">
    <y-table
      ref="guardianTable"
      border
      pagination
      :getDataWay="guardianDataWay"
      :columns="guardianColumns"></y-table>
  </el-dialog>
  <y-form
    v-model="stepForms.formModel"
    :visible.sync="stepForms.showForm"
    :title="'编辑阶段【' + stepForms.adoptedName + '】'"
    destroy-on-close
    width="50%"
    :form-attrs="stepForms.formAttrs"
    :columns="stepFormColumns"
    @ensure="ensureStepModel">
  </y-form>
</div>
</template>

<script>
import adoptedDetails from "./adoptedDetails/adoptedDetails";
import adoptedDetailsBatch from "./adoptedDetails/adoptedDetailsBatch";
import adoptOrderInfo from "../adopt/adoptOrderDetails/adoptOrderInfo";
export default {
  name: "adoptedList",
  components: { adoptedDetails, adoptedDetailsBatch, adoptOrderInfo },
  inject: ['getDictNameSync', 'generateMediaUrl','getEnum'],
  provide(){
    return{
      getVarietyName: this.getVarietyName,
      refreshList: this.searchTable
    }
  },
  computed: {
    getDataWay(){
      return {
        dataType: 'url',
        data: this.$api.adopted.queryAdoptedInfoList,
        param: this.search
      }
    },
    guardianDataWay(){
      return {
        dataType: 'url',
        data: this.$api.adopted.queryAdoptedUserList,
        param: {
          adoptedId: this.guardianForms.row ? this.guardianForms.row.id : ''
        }
      }
    },
    varietyVal:{
      get(){
        let ary = [];
        if(this.search.kind){
          ary.push(this.search.kind);
          if(this.search.variety){
            ary.push(this.search.variety);
          }
        }
        return ary;
      },
      set(val = []){
        val = val || [];
        [this.search.kind = '', this.search.variety = ''] = val;
      }
    },
    stepFormColumns(){
      return [
        {
          label: "当前阶段",
          prop: "adoptedStatus",
          comp:{
            compType: 'select',
            options: this.adoptedStatusOptions
          }
        }
      ]
    }
  },
  created() {
    this.$yAxios({
      url: this.$api.adopt.queryAdoptCategory
    }, info => {
      this.cateData = info;
    })
  },
  data(){
    return{
      adoptedStatusOptions: this.getEnum('adoptedStatus'),
      refreshKey: 0,
      search:{
        adoptedSn: '',
        adoptedName: '',
        kind: '',
        variety: '',
        adoptedUserName: '',
        status: '',
        adoptedStatus: ''
      },
      cateData: [],
      columns: [{
        label: "头像",
        prop: "avatarUrl",
        template: true
      },{
        label: "编号",
        prop: "adoptedSn",
        width: 90
      },{
        label: "名称",
        prop: "adoptedName",
        width: 80
      },{
        label: "种类",
        prop: "variety",
        template: true
      },{
        label: "规格",
        prop: "specJson",
        formatter: this.generateSpec,
        minWidth: 120
      },{
        label: "主养人",
        prop: "memberName",
        width: 100
      },{
        label: "开始时间",
        prop: "commitTime",
        width: 160,
        formatter(row){
          return (row.commitTime || '').replace('T', ' ');
        }
      },{
        label: "当前阶段",
        prop: "adoptedStatus",
        formatter: (function(row){
          return this.$$getArrayName(row.adoptedStatus, this.adoptedStatusOptions, { label: 'label', value: 'value' })
        }).bind(this),
        width: 80
      },{
        label: "建档操作",
        prop: "status",
        template: true
      }],
      importVisible: false,
      forms:{
        adoptedId: null,
        adoptedName: null,
        isEdit: false,
        showForm: false,
      },
      orderForms:{
        formsType: '',
        formTypeTitle: {
          'VIEW': '订单详情'
        },
        formsSize:{
          'VIEW': 800
        },
        currentForm: null,
        showForm: false,
      },
      guardianForms:{
        row: {},
        showForm: false,
      },
      stepForms:{
        adoptedId: '',
        adoptedName: '',
        formModel:{
          adoptedStatus: ''
        },
        formAttrs: {
          labelWidth: '100px'
        },
        showForm: false,
      },
      guardianColumns: [
        {
          label: "主人",
          prop: "adoptedUserName"
        },
        {
          label: "主人类型",
          prop: "adoptedUserType",
          formatter(row){
            switch(row.adoptedUserType){
              case '1': return '主养人';
              case '0': return '合养人';
              default: return '';
            }
          }
        },
        {
          label: "时间",
          prop: "createTime",
          formatter(row){
            return (row.createTime || '').replace('T', ' ');
          }
        }
      ]
    }
  },
  methods:{
    resetSearch(){
      Object.keys(this.search).map(key => this.search[key] = '');
    },
    searchTable(jumpToFirst){
      this.$refs['table'].loadData(this.search, jumpToFirst);
    },
    getVarietyName(kind, variety){
      if(!kind || !this.cateData.length) return '';
      let str = ''
      let kindObj = this.cateData.find(cd => cd.cateCode === kind);
      if(!kindObj) return '';
      str += kindObj.cateName;
      if(variety && kindObj.children && kindObj.children.length){
        let varietyObj = kindObj.children.find(vd => vd.cateCode === variety);
        if(varietyObj){
          str += '/' + varietyObj.cateName;
        }
      }
      return str;
    },
    generateSpec(row){
      if(!row.specJson) return '';
      else{
        let specJson = JSON.parse(row.specJson);
        let str = '';
        str += Object.values(specJson).join('；');
        return str;
      }
    },
    showGuardian(row){
      this.guardianForms.row = row;
      this.$nextTick(() => {
        this.guardianForms.showForm = true;
      })
    },
    editStatus(row){
      this.forms.adoptedId = row.id;
      this.forms.adoptedName = row.adoptedName;
      this.forms.isEdit = !row.adoptedStatus || ['0','1','3'].includes(row.adoptedStatus);
      this.forms.showForm = true;
    },
    editStep(row){
      this.stepForms.adoptedId = row.id;
      this.stepForms.adoptedName = row.adoptedName;
      this.stepForms.formModel.adoptedStatus = row.adoptedStatus || '';
      this.stepForms.showForm = true;
    },
    confirmStatus(row){
      this.$yAxios({
        url: this.$api.adopted.confirmAdopted,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '建档成功'
        });
        this.searchTable();
      })
    },
    openRefund(row){
      this.$yAxios({
        url: this.$api.adopted.openAdoptedRefund,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '成功开启退款'
        });
        this.searchTable();
      })
    },
    viewOrder(row){
      this.orderForms.currentForm = row;
      this.orderForms.showForm = true;
    },
    toHarvest(row){
      this.$yAxios({
        url: this.$api.adopted.updateAdoptedStatus,
        data:{
          adoptedId: row.id,
          adoptedStatus: '1'
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '物品阶段已置为[待收获]'
        });
        this.searchTable();
      })
    },
    ensureStepModel(form){
      this.$yAxios({
        url: this.$api.adopted.updateAdoptedStatus,
        data:{
          adoptedId: this.stepForms.adoptedId,
          adoptedStatus: form.adoptedStatus
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '保存阶段成功'
        });
        this.searchTable();
      })
    },
    closeDrawer(){
      this.forms.showForm = false;
      this.refreshKey ++ ;
    },
    onOpenGuardianPerson(){
      //this.$refs['guardianTable'].loadData(this.guardianDataWay.param);
    },
    hideGuardianPerson(){
      this.guardianForms.row = {};
    },
  }
}
</script>

<style scoped lang="less">
.adoptedList{
  .SearchBlock{
    /deep/ .el-form-item{
      width: 33.3333333333%;
      .el-form-item__content{
        max-width: 300px;
      }
    }
  }
}
</style>